% section 6.5 Benchmarking the Loss from Using Flat-Income Optimal
% Contracts
% this file shows the differences in CE for GHHW and GLTHI 
% capping state 7 expenditures

clear;
addpath functions
load('./results/model_parameters_main.mat')
load('./results/capHtmod_c.mat');
load('./results/allstates_main.mat')
iX = simulation_output.iX;
replicate = 1;

% I. calculate fee to finance cap

if replicate==1
    iXfolder = './results/iX_submission/';
else
    iXfolder = './results/iX_out/';
end

T = 70;
PO_sim = zeros(8,1);
transfer = model_parameters.MU(7,1,1)-model_parameters.MU(6,1,1);
for i=1:6
     fileName = [iXfolder,sprintf('iX_%d.mat',i)];
     rho = model_parameters.rho;
     load(fileName)
     Num_i = mean(sum((iX==7).*power(rho,(1:T)-1)',1));
     Den_i = mean(sum((iX~=8).*power(rho,(1:T)-1)',1));
     PO_sim(i)  = 1000*transfer*Num_i/Den_i;
end

% II. compute CE's bounding expenses of state 7 
clearvars -except PO_sim iXfolder;
load('./results/model_parameters_main.mat')
load('./results/allstates_main.mat')
load('./results/capHtmod_c.mat');
results_main = simulation_output.maintable;
load([iXfolder,'iX_main.mat']);

model_parameters.capHtmod= capHtmod_c;
model_parameters.outputfile ='./results/MU_alt_state7.mat';

MU = model_parameters.MU;
MU_alt = MU;
MU_alt(7,:,:)= MU(6,:,:);
model_parameters.MU  = MU_alt;

model_parameters.outputfile ='./results/MU_alt_state7.mat';
model_output_it = solve_main(model_parameters,iX);

results_it = model_output_it.maintable;
results_it = table2array(results_it(:,{'CE_FB','CE_ST','CE_GHHW','CE_GLTHI'}));

results_alt = results_it-capHtmod_c*PO_sim;
main_table_alt = array2table(results_alt);
main_table_alt = renamevars(main_table_alt,["results_alt1","results_alt2","results_alt3","results_alt4"],...
                        ["CE_FB","CE_ST","CE_GHHW","CE_GLTHI"]);

main_table_alt.gainsGHHW = (main_table_alt.CE_GHHW-main_table_alt.CE_ST)./(main_table_alt.CE_FB-main_table_alt.CE_ST);
main_table_alt.gainsGLTHI = (main_table_alt.CE_GLTHI-main_table_alt.CE_ST)./(main_table_alt.CE_FB-main_table_alt.CE_ST);
main_table_alt.metric1 = main_table_alt.gainsGLTHI./main_table_alt.gainsGHHW;
main_table_alt.metric2 = (main_table_alt.CE_GHHW-main_table_alt.CE_GLTHI)./(main_table_alt.CE_GHHW);

writetable(main_table_alt,'../../figsandtabs/table_robustness_state7.xlsx')    




 
